import React from 'react';
import './brandinfo.less';
import { Layout, Breadcrumb, Icon, Button, Table, message, Input, Select, Form, Pagination, Modal, Popconfirm, Checkbox } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token')



const CollectionCreateForm = Form.create()(
    class extends React.Component {
        render() {
            const { visible, onCancel, onCreate, form, isUsed, isEditing,closable = false, destroyOnClose = true ,checked} = this.props;
            const { getFieldDecorator,setFieldsValue } = form;
            return (
                <Modal
                    visible={visible}
                    title={isEditing?'修改品牌':"创建品牌"}
                    onCancel={onCancel}
                    onOk={onCreate}
                    maskClosable={closable}
                    destroyOnClose={destroyOnClose}
                >
                    <Form layout="vertical">
                        <FormItem>
                            {getFieldDecorator('brandName', {
                                rules: [{ required: true, message: '请输入品牌名称' }]
                            })(<Input addonBefore="品牌名称" />)}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('manufacturer', {
                                rules: [{ required: true, message: '请输入厂家名称' }]
                            })(<Input addonBefore="厂家名称" />)}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('remark')(<Input addonBefore="填写备注" />)}
                        </FormItem>
                        <FormItem>
                            选择状态：
                            {getFieldDecorator('beactive', { valuePropName: 'checked' ,initialValue:true})(<Checkbox>启用</Checkbox>)}
                        </FormItem>
                        {'isUsed' === 'Y' ? <div style={{ color: '#ff0000' }}>该品牌已被商品使用，如做修改会对现有产品产生影响，请谨慎操作。</div> : ''}
                    </Form>
                </Modal>
            );
        }
    }
);

class RegForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            brandlist: [],//时空商品信息
            brandcount: 0,//时空商品条数
            pagesize: 20,// 每页显示的页数
            pageindex: 1,// 当前页
            brandName: undefined,//品牌名
            manufacturer: undefined,//生产厂家
            beactive: undefined,//是否删除
            detailVisible: false,
            detailLoading: false,
            isEditing: '',//是否是编辑
            isUsed: 'N',//标志是否被使用
            checked:true,
            sort:'asc'
        }
    }

    componentDidMount() {
        this.GetBrandList();
    }
    //品牌信息列表
    GetBrandList() {
        $.ajax({
            url: `${config.brandManagement}/brand/list`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                brandName: this.state.brandName,
                manufacturer: this.state.manufacturer,
                beactive: this.state.beactive
            },
            async: true,
            success: res => {
                console.log('品牌列表', res)
                if (res.code === 200) {
                    res.data.rows.forEach((item, index) => {
                        item.key = index
                    })
                    this.setState({
                        brandlist: res.data.rows,
                        brandcount: res.data.count,
                    })
                }
            }
        });
    }
    //排序
    sortlist(){
        var sortby=this.state.sort;
        if(this.state.sort=='asc')sortby='desc';
        if(this.state.sort=='desc')sortby='asc';
        $.ajax({
            url: `${config.brandManagement}/brand/list`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                pageSize: this.state.pagesize,
                page: this.state.pageindex,
                brandName: this.state.brandName,
                manufacturer: this.state.manufacturer,
                beactive: this.state.beactive,
                sort:this.state.sort
            },
            async: true,
            success: res => {
                console.log('品牌列表', res)
                if (res.code === 200) {
                    res.data.rows.forEach((item, index) => {
                        item.key = index
                    })
                    this.setState({
                        brandlist: res.data.rows,
                        brandcount: res.data.count,
                        sort:sortby
                    })
                }
            }
        });
    }
    // 分页
    changePage(pageindex) {
        this.setState({
            pageindex
        }, () => {
            this.GetBrandList();
        });
    }

    //搜索
    SearchBrandInfoBtn(e) {
        const form = this.props.form;
        this.setState({
            pageindex: 1,
            brandName: form.getFieldValue('txt_BrandName'),
            manufacturer: form.getFieldValue('txt_Manufacturer')
        }, () => {
            this.GetBrandList()
        });
    }

    //重置
    ResetBtn(e) {
        const form = this.props.form;
        form.resetFields();
        this.setState({
            pageindex: 1,
            brandName: undefined,
            manufacturer: undefined,
            beactive: undefined
        }, () => {
            this.GetBrandList()
        });
    }

    handleRef(form) {
        this.brandForm = form
    }
    detail(values) {
        if (values) {
            this.inquiry(values.brandId);
        } else {
            this.setState({
                isUsed: 'N'
            })
        }
        let that = this;
        console.log(values);
        this.setState({
            detailVisible: true,
        }, () => {
            if (values) {
                this.setState({
                    isEditing: values,

                });
                let abc = (values.beactive == 'Y' ? true : false)
                console.log(abc)
                this.brandForm.setFieldsValue({
                    brandName: values.brandName,
                    manufacturer: values.manufacturer,
                    remark: values.remark,
                    beactive: abc
                })

            } else {
                this.setState({
                    isEditing: '',
                });
            }
        })
    }
    handleCreate(e) {
        e.preventDefault();
        this.brandForm.validateFields((err, values) => {
            if (err) {
                return;
            }
            if (this.state.isEditing) {
                $.ajax({
                    url: `${config.brandManagement}/brand/update`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        brandName: values.brandName,
                        manufacturer: values.manufacturer,
                        beactive: values.beactive ? 'Y' : 'N',
                        remark: values.remark,
                        brandId: this.state.isEditing.brandId,
                    },
                    async: true,
                    success: res => {
                        if (res.code === 200) {
                            message.success('修改品牌成功', 2)
                            this.brandForm.resetFields();
                            this.setState({
                                detailVisible: false
                            }, () => this.GetBrandList());
                        } else {
                            message.error(res.mes, 2)
                        }
                    }
                });
            } else {
                console.log('Received values of form: ', values);
                $.ajax({
                    url: `${config.brandManagement}/brand/add`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        brandName: values.brandName,
                        manufacturer: values.manufacturer,
                        beactive: values.beactive ? 'Y' : 'N',
                        remark: values.remark,
                    },
                    async: true,
                    success: res => {
                        if (res.code === 200) {
                            message.success('保存品牌成功', 2)
                            this.brandForm.resetFields();
                            this.setState({
                                detailVisible: false
                            }, () => this.GetBrandList());
                        } else {
                            message.error(res.mes, 2)
                        }
                    }
                });
            }
        });
    }

    saveFormRef(formRef) {
        this.formRef = formRef;
    }

    brandModelClose() {
        const form = this.formRef.props.form;
        form.resetFields();
        this.setState({
            detailVisible: false,
        })
    }

    brandStatusChange(v) {
        this.setState({
            beactive: v
        });
    }
    //修改状态
    deleteBrand(id, beactive) {
        const form = this.formRef.props.form;
        console.log("修改状态 " + id, beactive)
        let self = this
        $.ajax({
            url: `${config.brandManagement}/brand/stateChanges`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                brandId: id,
                beactive: beactive == 'Y' ? 'N' : 'Y',
            },
            async: true,
            success: res => {

                if (res.code === 200) {
                    let alls = self.state.brandlist.map((item) => {
                        if (item.brandId == id) {
                            item.beactive = item.beactive == 'Y' ? 'N' : 'Y'
                            return item;
                        }
                        return item;
                    })
                    // message.success('修改成功', 2)
                    // form.resetFields();
                    self.setState({ brandlist: alls }, () => this.GetBrandList())
                } else {
                    message.error(res.mes, 2)
                }
            }
        });
    }

    //查询品牌是否被使用
    inquiry(id) {
        const form = this.formRef.props.form;
        console.log("查询品牌是否被使用 " + id)
        $.ajax({
            url: `${config.brandManagement}/brand/isUsed`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                brandId: id,
            },
            async: true,
            success: res => {
                if (res.code === 200) {
                    console.log(res.mes)
                    this.setState({
                        isUsed: res.mes
                    })
                }
            }
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const title = (
            <span>
              状态
                <Icon style={{ marginLeft: '0.25em' }} type="swap" onClick={()=>{this.sortlist()}}/>
            </span>
          );
        const columns = [
            {
                title: '品牌名称',
                dataIndex: 'brandName',
                width: '6%',
                render: (text, record) => {
                    return <div>{text}</div>;
                }
            },
            {
                title: '厂家名称',
                dataIndex: 'manufacturer',
                width: '7%',
                render: (text, record) => {
                    return <div>{text}</div>;
                }
            },
            {
                title: '备注',
                dataIndex: 'remark',
                width: '7%',
                render: (text, record) => {
                    return <div>{text}</div>;
                }
            },
            {
                title: title,
                dataIndex: '',
                width: '4%',
                render: (record) => {
                    if (record.beactive == "Y") {
                        return <Popconfirm title="您确定要关闭么？" okText="是" cancelText="否" onConfirm={this.deleteBrand.bind(this, record.brandId, record.beactive)}>
                            <a href="javascript:void(0)'">开启</a>
                        </Popconfirm>
                    } else {
                        return <Popconfirm title="您确定要开启么？" okText="是" cancelText="否" onConfirm={this.deleteBrand.bind(this, record.brandId, record.beactive)}>
                            <a href="javascript:void(0)'">关闭</a>
                        </Popconfirm>;
                    }
                }
            },
            {
                title: '操作',
                dataIndex: '',
                width: '4%',
                render: (text, record) => {
                    return <p>
                        <a href='javascript:void(0)' onClick={this.detail.bind(this, record, )}>修改</a>
                        {/* <Popconfirm title="您确定要删除么？" okText="是" cancelText="否" onConfirm={this.deleteBrand.bind(this, record.brandId, record.beactive)}>
                                <a href="javascript:void(0)'">修改</a>
                            </Popconfirm> */}

                    </p>
                }

            }
        ]
        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>首页</Breadcrumb.Item>
                                <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                                <Breadcrumb.Item>品牌管理</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd addetd-z'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_BrandName')(
                                            <Input className='addetd-a-r' addonBefore="品牌名" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-z'>
                                <FormItem>
                                    {
                                        getFieldDecorator('txt_Manufacturer')(
                                            <Input className='addetd-a-r' addonBefore="厂家名称" placeholder="请输入" />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <Button type="primary" className='member-button' icon="search" onClick={this.SearchBrandInfoBtn.bind(this)}>搜索</Button>
                            <Button type="primary" className='member-button' icon="reload" onClick={this.ResetBtn.bind(this)}>重置</Button>
                        </div>
                        {/* <div className='rowchangereds'>注：标红的行已删除</div> */}
                        <div className='allgoods-table clearfix'>
                            <Table
                                columns={columns}
                                dataSource={this.state.brandlist}
                                pagination={false}
                                bordered
                            />
                            <div className='goods-label-tabletr'>
                                <Button className='goods-label-table-app' width={160} icon="plus" onClick={() => this.detail()}>新增</Button>
                            </div>
                        </div>
                        <div className='goods-label-let'>
                            <div className="floor-ppagi">
                                {
                                    this.state.brandcount == 0 ?
                                        <p className="floor-ppagip">
                                            共{this.state.brandcount}条记录
                                </p> :
                                        <p className="floor-ppagip">
                                            当前显示
                                    {this.state.pagesize * (this.state.pageindex - 1) + 1}—
                                    {this.state.pagesize * this.state.pageindex < this.state.brandcount ? this.state.pagesize * this.state.pageindex : this.state.brandcount}条记录，
                                    共{this.state.brandcount}条记录
                                </p>
                                }
                                <Pagination current={this.state.pageindex} total={this.state.brandcount || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                            </div>
                        </div>
                    </div>
                </div>
                <CollectionCreateForm
                    wrappedComponentRef={this.saveFormRef.bind(this)}
                    visible={this.state.detailVisible}
                    isUsed={this.state.isUsed}
                    isEditing={this.state.isEditing}
                    onCreate={this.handleCreate.bind(this)}
                    onCancel={this.brandModelClose.bind(this)}
                    ref={this.handleRef.bind(this)}
                    checked={this.state.checked}
                />
            </Form>
        )
    }
}

const Brandinfo = Form.create()(RegForm);
export default Brandinfo;